<template>
  <div class="main_box">
    <el-row class="header-row">
      <el-col>
        <div class="search_wrap">
          <el-form :inline="true" :model="filters" ref="searchForm">
            <el-form-item prop="menuName">
              <el-input v-model="filters.menuName" :clearable="true" placeholder="菜单名称"></el-input>
            </el-form-item>
            <el-form-item prop="menuCatetory">
              <el-select v-model="filters.menuCatetory" clearable placeholder="请选择菜单类别">
                <el-option key="1" label="系统" value="1"></el-option>
                <el-option key="2" label="H5" value="2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="menuCode">
              <el-input v-model="filters.menuCode" :clearable="true" placeholder="菜单编码"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button icon="el-icon-search" type="primary" @click="onSearch">查询</el-button>
              <el-button icon="el-icon-refresh-left" @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
      <el-col>
        <div class="opration_wrap">
          <el-tooltip content="刷新" placement="top">
            <el-button circle icon="el-icon-refresh-right" @click="reload" size="mini"></el-button>
          </el-tooltip>
          <el-button type="primary" plain icon="fa fa-plus" v-has="permissionAdd" @click="handleClickAdd()" size="mini">
            新增</el-button>
        </div>
      </el-col>
    </el-row>

    <el-row ref="tableRow">
      <!-- 列表 -->
      <tree-table :customRow="handleClickRow" :key='tableKey' :columns="columns" :data="treeTableList" :eval-func="func"
        :eval-args="args" :expand-all="expandAll" :height="maxHeight + 40" border>
        <el-table-column width="400px" align="center" label="菜单编码">
          <template slot-scope="scope">
            <span>{{ scope.row.menuCode }}</span>
          </template>
        </el-table-column>
        <el-table-column width="240px" label="资源路径">
          <template slot-scope="scope">
            <span class="">{{ scope.row.menuUrl }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="描述">
          <template slot-scope="scope">
            <span>{{ scope.row.descriptions }}</span>
          </template>
        </el-table-column>
        <el-table-column width="80px" align="center" label="排序(正序)">
          <template slot-scope="scope">
            <span>{{ scope.row.sortby }}</span>
          </template>
        </el-table-column>
        <el-table-column width="100px" align="center" label="状态">
          <template slot-scope="scope">
            <span>
              <el-tag size="mini" effect="plain" :type="formatStates(scope.row.state)">
                {{ formatState(scope.row.state) }}
              </el-tag>
            </span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="400px" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <div class="operate-box">
              <el-button v-has="permissionAdd" type="text" size="mini" icon="el-icon-document-add"
                @click="handleClickAddMenu(scope.row)" v-if="scope.row.menuType < 2">新增下级</el-button>
              <el-button v-has="permissionEdit" type="text" size="mini" icon="el-icon-edit"
                @click="handleClickEditor(scope.row)">编辑</el-button>
              <el-button v-has="permissionUpStatus" type="text" size="mini" icon="el-icon-check"
                @click="handleClickEnable(scope.row)" v-if="scope.row.state === 0">启用</el-button>
              <el-button v-has="permissionUpStatus" type="text" size="mini" icon="el-icon-close"
                @click="handleClickDisable(scope.row)" v-if="scope.row.state === 1">禁用</el-button>
              <el-button v-has="permissionDelete" v-if="scope.row.state === 0" type="text" size="mini"
                icon="el-icon-delete" @click="handleClickDelete(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </tree-table>
    </el-row>
  </div>
</template>
<script>
import * as message from "@/constants/message";
import AuthApi from "@/api/system/auth";
import treeToArray from '@/utils/customEval';
import treeTable from '@/components/TreeTable';

export default {
  name: 'MenuManagement',
  inject: ['reload'], //注入局部刷新
  data() {
    return {
      filters: {
        menuName: "",
        menuCode: "",
        menuCatetory: ''
      },
      tableKey: 0,
      total: null,
      func: treeToArray,
      args: [],
      list: {},
      treeTableList: [],
      //开始切割的位置
      starSize: 0,
      //结束位置
      endSize: 20,
      totalSize: [],
      // list2: undefined,
      expandAll: false,
      columns: [
        {
          text: '菜单名称',
          value: 'menuName',
          width: 220
        }
      ],
      maxHeight: 500,
      tableList: [],
      permissionAdd: 'SYSTEM_MANAGER_SYS_MENU_LIST_ADD',
      permissionEdit: 'SYSTEM_MANAGER_SYS_MENU_LIST_EDIT',
      permissionUpStatus: 'SYSTEM_MANAGER_SYS_MENU_LIST_STATE',
      permissionDelete: 'SYSTEM_MANAGER_SYS_MENU_LIST_DELETE',
    }
  },
  components: {
    treeTable
  },
  mounted() {
    this.init();
    window.addEventListener("keydown", this.keyDown);
  },
  activated() {
    if (this.$route.meta.keepAlive) {
      this.listTable();
    }
    if (this.$route.params.menuId) {
      let menuItem = this.tableList.filter(item => {
        return item.menuId == this.$route.params.menuId
      })
      let index = this.tableList.indexOf(menuItem[0]);
      for (let item in this.tableList[index]) {
        if (this.$route.params[item]) {
          this.tableList[index][item] = this.$route.params[item];
        }
      }
    }
  },
  destroyed() {
    window.removeEventListener("keydown", this.keyDown, false);
  },
  methods: {
    //懒加载1-节流函数
    throttle(fn, delay) {
      let valid = true;
      return function () {
        if (!valid) {
          //休息时间 暂不执行
          return false;
        }
        // 工作时间，执行函数并且在间隔期内把状态位设为无效
        valid = false;
        setTimeout(() => {
          fn();
          valid = true;
        }, delay);
      };
    },
    //懒加载2-触发方法
    triggerScroll() {
      document
        .querySelector("#scrollDiv .el-table__body-wrapper")
        .addEventListener("scroll", this.throttle(this.handleScroll, 1000));
    },
    //懒加载3-主体方法
    handleScroll() {
      let scrollTop = document.querySelector("#scrollDiv .el-table__body-wrapper").scrollTop;
      let scrollHeight = document.querySelector("#scrollDiv .el-table__body-wrapper").scrollHeight;
      let clientHeight = document.querySelector("#scrollDiv .el-table__body-wrapper").clientHeight;
      if (this.totalSize.length == this.treeTableList.length) {
        //表示已到底部
        return;
      }
      if (scrollHeight - clientHeight - scrollTop < 30) {
        //监听滚动条到底部
        this.starSize = this.starSize + 20;
        this.endSize = this.endSize + 20;
        let arrOne = this.treeTableList;
        let arrTwo = this.totalSize.slice(this.starSize, this.endSize);
        this.treeTableList = arrOne.concat(arrTwo);
      }
    },
    init() {
      this.getTableHeight();
      this.listTable();

    },
    keyDown(e) {
      //如果是回车则执行查询方法
      if (e.keyCode == 13) {
        this.onSearch();
      }
    },
    getTableHeight() {
      this.$nextTick(function () {
        this.maxHeight = window.innerHeight - this.$refs.tableRow.$el.offsetTop - 50;
        window.onresize = () => {
          this.maxHeight = window.innerHeight - this.$refs.tableRow.$el.offsetTop - 50;
        }
      })
    },

    listTable() {
      let _this = this
      _this.starSize = 0
      _this.endSize = 20
      let data = {
        menuName: _this.filters.menuName,
        menuCode: _this.filters.menuCode,
        menuCatetory: _this.filters.menuCatetory,
      };
      _this.$emit('show-loading', true);
      AuthApi.listMenuTreeTable(data)
        .then(res => {
          _this.totalSize = res.data;
          if (_this.totalSize.length > 20) {
            _this.treeTableList = _this.totalSize.slice(
              _this.starSize,
              _this.endSize
            );

          } else {
            _this.treeTableList = _this.totalSize;
          }
          // _this.list = res.data
          _this.$emit('show-loading', false);
        }).catch(err => {
          _this.listLoading = false
        });
    },
    // listTable() {
    //   let _this = this
    //   let data = {
    //     menuName: _this.filters.menuName,
    //     menuCode: _this.filters.menuCode
    //   };
    //   _this.$emit('show-loading',true);
    //   AuthApi.listMenuTreeTable(data)
    //     .then(res => {
    //       _this.list = res.data
    //       _this.$emit('show-loading',false);
    //     })
    // },
    handleClickAdd() {
      this.$router.push({ path: "/sys/menuAdd", query: { id: "0" } });
    },
    handleClickAddMenu(row) {
      this.$router.push({ path: "/sys/menuAdd", query: { id: row.menuId } });
    },
    handleClickEditor(row) {
      this.$router.push({ path: "/sys/menuEdit", query: { id: row.menuId } });
    },
    handleClickDisable(row) {
      this.$confirm(message.MSG_CONFIRM_DISABLE, message.TITLE_PROMPT, {})
        .then(() => {
          this.deleteData(row, 0);
        })
    },
    handleClickEnable(row) {
      this.$confirm(message.MSG_CONFIRM_ENABLE, message.TITLE_PROMPT, {})
        .then(() => {
          this.deleteData(row, 1);
        })
    },
    handleClickDelete(row) {
      this.$confirm(message.MSG_CONFIRM_DELETE, message.TITLE_PROMPT, {})
        .then(() => {
          this.deleteData(row, -1);
        })
    },
    deleteData(row, currentState) {
      let data = {
        menuId: row.menuId,
        state: currentState
      };
      AuthApi.updateMenuState(data)
        .then(res => {
          if (data.state != -1) {
            row.state = data.state;
          } else {
            this.listTable();
          }
          this.$Utils.notifySuccess()
        })
    },
    formatType(cellValue) {
      if (cellValue === 0) {
        return "菜单分组"
      } else if (cellValue === 1) {
        return "功能菜单"
      } else if (cellValue === 2) {
        return "菜单按钮"
      }
    },
    formatState(cellValue) {
      if (cellValue === -1) {
        return "删除"
      } else if (cellValue === 0) {
        return "禁用"
      } else if (cellValue === 1) {
        return "启用"
      }
    },
    formatStates(cellValue) {
      if (cellValue === -1) {
        return "danger"
      } else if (cellValue === 0) {
        return "warning"
      } else if (cellValue === 1) {
        return "success"
      }
    },
    onSearch() {
      this.listTable();
    },
    resetForm() {
      this.$refs.searchForm.resetFields();
      this.onSearch()
    },

    handleClickRow(record, index) {
      return {
        on: {
          click: () => {
            console.log(record, index)
            console.log('点击行内容record' + record)
            console.log('序号索引index' + index)
          }
        }
      }
    }

  }
};
</script>
<style lang="scss">
@import "@/assets/css/views/content.scss";
</style>
